<template>
  <div class="upload-container">
    <!-- 标题 -->
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <div class="title">好的创作值得一个好名字！</div>
      <button @click="goToHome">返回</button>
    </div>

    <!-- 上传类型切换 -->
    <div class="upload-type-switch">
      <el-radio-group v-model="uploadType">
        <el-radio label="image">上传图片</el-radio>
        <el-radio label="video">上传视频</el-radio>
      </el-radio-group>
    </div>

    <!-- 上传区域 -->
    <div class="upload-box">
      <div
        class="upload-area"
        @click="handleUploadClick"
        :style="{
          backgroundImage: `url(${previewUrl})`,
          backgroundSize: 'contain',
          backgroundRepeat: 'no-repeat',
          backgroundPosition: 'center',
        }"
      >
        <div class="upload-overlay" v-if="!isUploaded">
          <i class="el-icon-plus"></i>
          <div class="upload-text">
            点击上传{{ uploadType === "image" ? "图片" : "视频" }}
          </div>
        </div>
        <input
          ref="fileInput"
          type="file"
          :accept="uploadType === 'image' ? 'image/*' : 'video/*'"
          class="file-input"
          @change="handleFileChange"
        />
      </div>

      <!-- 视频封面选择（上传视频后显示） -->
      <div class="cover-section" v-if="isUploaded && uploadType === 'video'">
        <div class="cover-title">选择封面</div>
        <div class="cover-list">
          <div
            v-for="(cover, index) in coverList"
            :key="index"
            class="cover-item"
            @click="selectCover(index)"
            :class="{ active: selectedCoverIndex === index }"
          >
            <img :src="cover" alt="cover" />
          </div>
        </div>
      </div>
    </div>

    <!-- 表单 -->
    <el-form class="form-container" label-width="80px">
      <el-form-item label="作品标题">
        <el-input
          v-model="form.blogName"
          placeholder="好的创作值得一个好名字！"
        />
      </el-form-item>

      <el-form-item label="所属分类">
        <el-select v-model="form.typeId" placeholder="请选择分类">
          <el-option
            v-for="item in categoryOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="内容">
        <el-input
          type="textarea"
          v-model="form.content"
          placeholder="请输入内容..."
          rows="6"
        />
      </el-form-item>
    </el-form>
  </div>
  <div style="display: flex; justify-content: center">
    <button @click="publishNote">发布笔记</button>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from "vue";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio,
  ElMessage,
} from "element-plus";
import { findAllType, uploadFileToServer, addImg ,uploadFileToMinio,addVideo} from "@/api/life";
import router from "@/router";
// import { type } from 'node:os';
// 响应式数据 - 表单
const form = reactive({
  userId: "",
  blogName: "",
  category: "",
  content: "",
  typeId: "",
  img: "",
});

const categoryOptions = ref([]); // 改为 ref 定义

const TestBucket = "your-fixed-bucket"; 

// 响应式数据 - 上传相关
const uploadType = ref("image"); // 默认上传图片，可切换为 'video'
const fileInput = ref(null);
const isUploaded = ref(false);
const file = ref(null); // 存储上传的文件（图片或视频）
const previewUrl = ref(""); // 预览图（图片或视频封面）
const coverList = ref([]); // 视频封面列表
const selectedCoverIndex = ref(0); // 选中的视频封面索引

// 模拟生成视频封面（实际可通过视频截图实现）
function generateCovers(videoFile) {
  return new Promise((resolve) => {
    const video = document.createElement("video");
    video.src = URL.createObjectURL(videoFile);
    video.addEventListener("loadeddata", () => {
      const canvas = document.createElement("canvas");
      canvas.width = 200;
      canvas.height = 120;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      const cover1 = canvas.toDataURL("image/jpeg");

      // 再截一张模拟多个封面（实际可按不同时间点截取）
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      const cover2 = canvas.toDataURL("image/jpeg");

      resolve([cover1, cover2]);
    });
  });
}

//发布笔记
const publishNote = async () => {
  //判断是上传图片还是上传视频
  if (uploadType.value === "image") {
    form.category = "图片";
    const res = await addImg(form);
    console.log("发布笔记获取到的返回值" + JSON.stringify(res));
    if (res.code === 200) {
      ElMessage.success("图片上传成功");
      // 返回
      router.push("/LifePerson");
    } else {
      // 处理错误情况
      ElMessage.error(res.message || "上传失败，请重试");
    }
  } else {
    // 处理视频上传逻辑
    form.category = "视频";
    // const res = await addVideo(form);
    const res = await addVideo(form);
    if (res.code === 200) {
      ElMessage.success("视频上传成功");
      // 返回
      router.push("/LifePerson");
    } else {
      ElMessage.error(res.message || "视频上传失败");
    }
  }
};

//返回个人笔记界面
const goToHome = async () => {
  await new Promise((resolve) => setTimeout(resolve, 50));
  router.push("/LifePerson");
};

// 点击上传区域
function handleUploadClick() {
  fileInput.value.click();
}

// 选择文件后
async function handleFileChange(e) {
  const selectedFile = e.target.files[0];
  if (selectedFile) {
    file.value = selectedFile;
    isUploaded.value = true;
    if (uploadType.value === "image") {
      previewUrl.value = URL.createObjectURL(selectedFile); // 图片预览
      coverList.value = []; // 上传图片时清空封面列表
      try {
        const response = await uploadFileToServer(selectedFile);
        console.log("上传成功:", response.data);
        form.img = response.data;
      } catch (error) {
        console.error("上传失败:", error);
        // 重置状态
        isUploaded.value = false;
        previewUrl.value = "";
      }
    } else {
      previewUrl.value = URL.createObjectURL(selectedFile); // 视频预览（临时用视频本身做预览，实际可优化）
      coverList.value = await generateCovers(selectedFile); // 生成视频封面
      try {
        const response = await uploadFileToMinio(selectedFile);
        console.log("上传成功:", response.data);
        form.video = response.data;
      } catch (error) {
        console.error("上传失败:", error);
        // 重置状态
        isUploaded.value = false;
        previewUrl.value = "";
      }
    }
  }
}

// 选择视频封面
function selectCover(index) {
  selectedCoverIndex.value = index;
  previewUrl.value = coverList.value[index];
}

// 监听上传类型切换，重置状态
watch(uploadType, (newType) => {
  isUploaded.value = false;
  file.value = null;
  previewUrl.value = "";
  coverList.value = [];
  selectedCoverIndex.value = 0;
  // 清空文件输入框
  if (fileInput.value) {
    fileInput.value.value = "";
  }
});

// 获取所有类型
const selectAllType = async () => {
  try {
    const res = await findAllType();
    categoryOptions.value = res.data;
    console.log("获取到的type列表:" + JSON.stringify(res.data));
  } catch (error) {
    console.error("获取类型失败:", error);
  }
};

//获取用户的userId（从localStorage读取实际登录用户ID）
const getUserId = () => {
  // 获取存储的 user 数据（JSON 字符串形式）
  const userStr = localStorage.getItem("user");
  // 解析成 JavaScript 对象
  const user = userStr ? JSON.parse(userStr) : null;
  if (user && user.userId) {
    form.userId = user.userId; // 更新为实际用户ID
    console.log("userId更新为:", form.userId);
    selectAllType();
  } else {
    console.log("localStorage 中未找到有效的 user 数据");
  }
};

onMounted(async () => {
  //获取登录用户的id信息
  getUserId();
});
</script>

<style scoped>
.upload-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

/* 标题样式 */
.title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

/* 上传类型切换样式 */
.upload-type-switch {
  margin-bottom: 15px;
}

/* 上传区域样式 */
.upload-box {
  position: relative;
  margin-bottom: 30px;
}

.upload-area {
  width: 300px;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-overlay {
  text-align: center;
  color: #999;
}

.upload-text {
  margin-top: 8px;
}

.file-input {
  display: none;
}

/* 封面选择样式 */
.cover-section {
  margin-top: 20px;
}

.cover-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.cover-list {
  display: flex;
  gap: 10px;
}

.cover-item {
  width: 100px;
  height: 60px;
  border: 2px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cover-item:hover {
  border-color: #409eff;
}

.cover-item.active {
  border-color: #409eff;
}

.cover-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 表单样式 */
.form-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>
